<template>
  <BasicsForm
    :disabled="formDisabled"
    :btnGroupOptions="btnGroupOptions"
    :formInteractionMode="formInteractionMode"
    @register="register"
    @submit="onSubmit"
    @onSchemaChange="onChange"
  />
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormProps } from '@/components/Form';
  import { memberTypeGetList, customModuleType } from '@/api/membership';
  import { onMounted, type PropType, reactive, ref, watchEffect } from 'vue';
  import { IsInternalInterfaceEnum, IsRequired } from '@/enums/formEnum';
  import dictionary from '@/utils/dictionary';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import type { customFormUserAnswerList } from '@/api/membership/types';
  import { type FormItemVoMapItem } from '@/api/membership/formCompTypes';
  import { AuditStatusEnum } from '@/enums/membershipEnum';
  import { MemberRoleEnum } from '@/enums/memberRoleEnum';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { storeToRefs } from 'pinia';
  import { getTianyanchaDetail } from '@/components/Form/utils/tianyancha';
  import type { OnchangeArgument } from '@/components/Form/types';
  import { type CardBottomBtnsOptions } from '@/components/TButtonGroup/types';
  import { useUpload } from '@/hooks/core/useUpload';
  import { useEnv } from '@/hooks/core/useEnv';
  import { Api } from '@/api/membership';
  import { useAppStoreWithOut } from '@/store/modules/app';

  const props = defineProps({
    auditStatus: Number as PropType<AuditStatusEnum>,
    formItemMap: {
      type: Object as PropType<FormItemVoMapItem>,
      required: true,
    },
    answerList: {
      type: Array as PropType<customFormUserAnswerList[]>,
      required: true,
    },
  });
  const emit = defineEmits(['onLoad', 'onSubmit', 'onChange']);

  const [register, { appendSchemaByField, updateSchema, setFieldsValue }] = useForm({
    labelPosition: 'left',
    labelAlign: 'left',
    labelWidth: 140,
    validateTrigger: 'bind',
    schemas: [],
  });

  const { getEnv } = useEnv();
  const { openDocument } = useUpload();
  const { globalConfig } = useAppStoreWithOut();

  const btnGroupOptions = reactive<CardBottomBtnsOptions>({
    custom: {
      text: '下载入会表',
      clickFn: (e) => {
        openDocument({
          filePath: getEnv('BASE_URL') + Api.membershipFormPdf,
          fileType: 'pdf',
          customFileName: `${globalConfig?.name}入会申请表`,
        });
      },
    },
    submit: {
      text: '提交审核',
    },
  });

  const useUser = useUserStoreWithOut();
  const { cocInfo } = storeToRefs(useUser);

  const formDisabled = ref(false);
  const formInteractionMode = ref<FormProps['formInteractionMode']>('normal');

  function isEdit() {
    const { auditStatus } = props;
    if (cocInfo.value.memberRoleType === MemberRoleEnum.MEMBER) {
      formDisabled.value = true;
      formInteractionMode.value = 'details';
      btnGroupOptions.submit = void 0;
      return;
    }

    if (auditStatus === AuditStatusEnum.CHECKPENDING) {
      formDisabled.value = true;
      formInteractionMode.value = 'details';
      setBtnText('审核中', true);
    } else {
      formDisabled.value = false;
      formInteractionMode.value = 'normal';
      setBtnText('提交审核');
    }
  }

  function setBtnText(text: string, disabled?: boolean) {
    if (btnGroupOptions.submit) {
      btnGroupOptions.submit.text = text;
      btnGroupOptions.submit.disabled = disabled;
    }
  }

  /** 获取表单模板 */
  async function getFormComp() {
    const { formItemMap, answerList } = props;

    const moduleType = await customModuleType();
    const typeDataName: { type: string; field: string }[] = [];
    const dictDataName: { type: string; field: string }[] = [];
    for (const key in formItemMap) {
      const label = moduleType.find((v) => v.id == (key as unknown as number))?.name;
      const formItem = formItemMap[key];
      appendSchemaByField({
        field: 'Divider' + key,
        component: 'Divider',
        label,
      });
      for (let i = 0; i < formItem.length; i++) {
        const v = formItem[i];

        const field = v.id.toString();
        if (v.isInternalInterface === IsInternalInterfaceEnum.CLASSIFICATION)
          typeDataName.push({ field, type: v.type });
        if (v.isInternalInterface === IsInternalInterfaceEnum.DICTIONARY)
          dictDataName.push({ field, type: v.type });
        const component = v.itemType;
        const dynamicDisabled = formDisabled.value ? true : v.disabled;
        const defaultValue = answerList.find((item) => item.formItemId == v.id)?.content;

        appendSchemaByField({
          field,
          component,
          label: v.showName,
          dataType: v.dataType,
          isInternalInterface: v.isInternalInterface,
          required: v.isRequired === IsRequired.REQUIRED,
          defaultValue: defaultValue,
          dynamicDisabled: v.type === 'memberLevel' ? true : dynamicDisabled,
          componentProps: {
            placeholder: v.value,
            limit: v.length,
            itemDefault: v.itemDefault,
            enableValue: v.enableValue,
            localdata: localDataMapping(v.customFormItemAnswerList, {
              label: 'words',
              value: 'id',
            }),
          },
        });
      }
    }

    await getFieldLocaldata(typeDataName, dictDataName);

    emit('onLoad');
  }

  async function getFieldLocaldata(
    typeDataName: { type: string; field: string }[] = [],
    dictDataName: { type: string; field: string }[] = [],
  ) {
    const updateSchemasValue = [];
    if (typeDataName.length) {
      const res = await memberTypeGetList(typeDataName.map((v) => v.type));
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchemasValue.push({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(res[item.type], { label: 'name', value: 'id' }),
          },
        });
      }
    }

    if (dictDataName.length) {
      const dictList = await dictionary.getMulti(dictDataName.map((v) => v.type));
      for (let index = 0; index < dictDataName.length; index++) {
        const item = dictDataName[index];
        updateSchemasValue.push({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(dictList[item.type], {
              label: 'dictLabel',
              value: 'dictValue',
            }),
          },
        });
      }
    }

    updateSchema(updateSchemasValue);
  }

  onMounted(() => {
    isEdit();
    getFormComp();
  });

  function onSubmit(e: any) {
    emit('onSubmit', e);
  }

  function onChange(e: OnchangeArgument) {
    if (e.component === 'InputSearch' && e.val) {
      getTianyanchaDetail(e).then((values) => {
        values && setFieldsValue(values);
      });
      emit('onChange', e);
    }
  }
</script>

<style scoped></style>
